package com.mingmen.supplier.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.mingmen.supplier.R;
import com.mingmen.supplier.activity.CanCelOrderDetailActivity;
import com.mingmen.supplier.activity.LoginActivity;
import com.mingmen.supplier.adapter.CancelDingDanListAdapter;
import com.mingmen.supplier.adapter.DingDanListAdapter;
import com.mingmen.supplier.base.BaseBean;
import com.mingmen.supplier.flycotablelayout.flyco.tablayout.SegmentTabLayout;
import com.mingmen.supplier.http.callback.StringCallback;
import com.mingmen.supplier.httpconfig.HttpResponse;
import com.mingmen.supplier.model.DingListModel;
import com.mingmen.supplier.model.EventBean;
import com.mingmen.supplier.refresh.ClassicsFooter;
import com.mingmen.supplier.refresh.ClassicsHeader;
import com.mingmen.supplier.util.GsonUtil;
import com.mingmen.supplier.util.SharePreferenceUtil;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Response;

@SuppressLint("ValidFragment")
public class CanCelOrdelFragment extends BaseFragment implements CancelDingDanListAdapter.OnItemClickListener {
    @BindView(R.id.card_title_tv)
    TextView cardTitleTv;
    Unbinder unbinder;
    private String mTitle;
    //Fragment的View加载完毕的标记
    private boolean isLoading = false;

    //Fragment对用户可见的标记
    private boolean isUIVisible;

    public static CanCelOrdelFragment getInstance(String title) {
        CanCelOrdelFragment sf = new CanCelOrdelFragment();
        sf.mTitle = title;
        return sf;
    }

    CancelDingDanListAdapter commodityAdapter;

    List<DingListModel.DataBean> dataList = new ArrayList<>();

    LinearLayoutManager linearLayoutManager;
    @BindView(R.id.tl_4)
    SegmentTabLayout tabLayout_4;


    @BindView(R.id.recycle_shopo)
    RecyclerView mRecyclerView;
    @BindView(R.id.layout_nodata)
    LinearLayout layout_nodata;
    String token;
    TimePickerView pvTime;
    @BindView(R.id.textview_calendafirst)
    TextView textview_calendafirst;
    @BindView(R.id.textview_calendasecond)
    TextView textview_calendasecond;
    String startTime;
    String endTime;
    @BindView(R.id.layout_search)
    LinearLayout layout_search;
    @BindView(R.id.layout_second)
    LinearLayout layout_second;
    @BindView(R.id.btn_search)
    Button btn_search;
    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    int pageNumber = 1;
    int totalPage;
    @BindView(R.id.layout_alldata)
    LinearLayout layout_alldata;
    @BindView(R.id.img_jingying)
    ImageView img_jingying;
    @BindView(R.id.img_shangjia)
    ImageView img_shangjia;

    @Override
    public View initView() {
        View v = LayoutInflater.from(getActivity()).inflate(R.layout.fr_cancelorder, null);
        unbinder = ButterKnife.bind(this, v);
        TextView card_title_tv = (TextView) v.findViewById(R.id.card_title_tv);
        card_title_tv.setText(mTitle);
        EventBus.getDefault().register(this);
        token = (String) SharePreferenceUtil.get(getActivity(), "token", "");
        linearLayoutManager = new LinearLayoutManager(getActivity());
        getCaneda();
        mRecyclerView.setLayoutManager(linearLayoutManager);
        commodityAdapter = new CancelDingDanListAdapter(getActivity(), dataList);
        mRecyclerView.setAdapter(commodityAdapter);

        mRecyclerView.setVisibility(View.VISIBLE);
        if (dataList.size() > 0) {
            dataList.clear();
        }

//        commodityAdapter.setDataList(dataList);
        commodityAdapter.setOnItemClickListener(this);

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String data = dateFormat.format(calendar.getTime());

//        textview_calendafirst.setText(data);
//        textview_calendasecond.setText(data);
        String replace_data = data.replace("-", ".");
        Log.d("replace_data", replace_data);
        textview_calendafirst.setText(replace_data);
        textview_calendasecond.setText(replace_data);
        startTime = data;
        endTime = data;
        getData(token, "3", "", "", "", pageNumber);
        refreshLayout.setRefreshHeader(new ClassicsHeader(getActivity()));
        refreshLayout.setRefreshFooter(new ClassicsFooter(getActivity()));

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                if (dataList.size() > 0) {
                    dataList.clear();
                }
                pageNumber = 1;

//                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                getData(token, "3", "", startTime, endTime, pageNumber);
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                if (pageNumber >= totalPage) {
                    Toast.makeText(getActivity(), "已到最后一页", Toast.LENGTH_SHORT).show();
                    refreshlayout.finishLoadMore(false);//传入false表示加载失败
                } else {
                    pageNumber++;

//                    getData(token, "3", "", startTime, endTime, pageNumber);
                    HttpResponse.listOrder(token, "3", "", startTime, endTime, pageNumber, new StringCallback(getActivity()) {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {


                            BaseBean baseBean = new BaseBean();
                            baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                            if (baseBean.getCode() == 0) {
                                DingListModel dingListModel = new DingListModel();
                                dingListModel = GsonUtil.GsonToBean(s, DingListModel.class);
                                dataList.addAll(dingListModel.getData());
                                if (dataList.size() == 0) {
                                    layout_nodata.setVisibility(View.VISIBLE);
                                    layout_alldata.setVisibility(View.GONE);
                                } else {
                                    layout_nodata.setVisibility(View.GONE);
                                    layout_alldata.setVisibility(View.VISIBLE);
                                }
                                totalPage = dingListModel.getTotalPage();
                                commodityAdapter.setDataList(dataList);
                            } else if (baseBean.getCode() == 401) {
                                startActivity(new Intent(getActivity(), LoginActivity.class));
                                getActivity().finish();
                            } else {
                                Toast.makeText(getActivity(), baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                            }


                        }

                        @Override
                        public void onAfter(String s, Exception e) {
                            super.onAfter(s, e);
                            refreshLayout.finishRefresh(100/*,false*/);//传入false表示刷新失败
                            refreshLayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
                        }
                    });
                    refreshlayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
                }


            }
        });
        return v;
    }

    public void getData(String token, String st, String keyword, String startTime, String endTime, int pageNumber) {
        HttpResponse.listOrder(token, st, keyword, startTime, endTime, pageNumber, new StringCallback(getActivity()) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (dataList.size() > 0) {
                    dataList.clear();
                }

                BaseBean baseBean = new BaseBean();
                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {
                    DingListModel dingListModel = new DingListModel();
                    dingListModel = GsonUtil.GsonToBean(s, DingListModel.class);
                    dataList.addAll(dingListModel.getData());
                    if (dataList.size() == 0) {
                        layout_nodata.setVisibility(View.VISIBLE);
                        layout_alldata.setVisibility(View.GONE);
                    } else {
                        layout_nodata.setVisibility(View.GONE);
                        layout_alldata.setVisibility(View.VISIBLE);
                    }
                    totalPage = dingListModel.getTotalPage();
                    commodityAdapter.setDataList(dataList);
                } else if (baseBean.getCode() == 401) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                    getActivity().finish();
                } else {
                    Toast.makeText(getActivity(), baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                }


            }

            @Override
            public void onAfter(String s, Exception e) {
                super.onAfter(s, e);
                refreshLayout.finishRefresh(100/*,false*/);//传入false表示刷新失败
                refreshLayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
            }
        });
    }

    @Override
    public void initData() {

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.card_title_tv, R.id.textview_calendafirst, R.id.layout_search, R.id.layout_second, R.id.btn_search, R.id.textview_calendasecond})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_search:
            case R.id.textview_calendafirst:

            case R.id.layout_second:
            case R.id.textview_calendasecond:
                img_shangjia.setRotation(360);
                img_jingying.setRotation(360);
                img_jingying.setImageResource(R.mipmap.arrowblue_bottom);
                img_shangjia.setImageResource(R.mipmap.arrowblue_bottom);
                pvTime.show(layout_second);
                break;
            case R.id.btn_search:

                Integer i = startTime.compareTo(endTime);
                if (i > 0) {
                    Toast.makeText(getActivity(), "开始时间不能大于结束时间", Toast.LENGTH_SHORT).show();
                } else {
                    dataList.clear();
                    getData(token, "3", "", startTime, endTime, 1);
                }

                break;
        }
    }

    @Override
    public void onItemClickListener(View view, int pos, List<DingListModel.DataBean> myLiveList) {
        Intent intent = new Intent(getActivity(), CanCelOrderDetailActivity.class);
        intent.putExtra("billId", myLiveList.get(pos).getBillId());
        intent.putExtra("partCancelFlag", myLiveList.get(pos).getPartCancelFlag());
        intent.putExtra("partArriveFlag", myLiveList.get(pos).getPartArriveFlag());
        intent.putExtra("partRefuseFlag", myLiveList.get(pos).getPartRefuseFlag());
        startActivity(intent);
    }


    public void getCaneda() {
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(2020, 1, 1);
        Calendar endDate = Calendar.getInstance();
        int y = endDate.get(Calendar.YEAR);
        int m = endDate.get(Calendar.MONTH);
        int d = endDate.get(Calendar.DATE);
        endDate.set(y, m, d);
        pvTime = new TimePickerBuilder(getActivity(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                switch (v.getId()) {
                    case R.id.layout_search:
                    case R.id.textview_calendafirst:
//                        textview_calendafirst.setText(getTime(date));
                        String replace_data = getTime(date).replace("-", ".");
                        Log.d("replace_data", replace_data);
                        textview_calendafirst.setText(replace_data);
                        startTime = getTime(date);
                        break;
                    case R.id.textview_calendasecond:
                    case R.id.layout_second:
//                        textview_calendasecond.setText(getTime(date));
                        String replace_data1 = getTime(date).replace("-", ".");
                        Log.d("replace_data", replace_data1);
                        textview_calendasecond.setText(replace_data1);
                        endTime = getTime(date);

                        break;
                }

            }
        }).setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_custom_lunar, new CustomListener() {

                    @Override
                    public void customLayout(final View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvTime.returnData();
                                pvTime.dismiss();

                                img_shangjia.setRotation(180);
                                img_jingying.setRotation(180);
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvTime.dismiss();

                                img_shangjia.setRotation(180);
                                img_jingying.setRotation(180);
                            }
                        });

                    }


                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(getResources().getColor(R.color.canedacolor))
                .setOutSideCancelable(false)
                .build();
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    public void onEventMainThread(EventBean eventBean) {
        if (eventBean.getSendCode() == 18) {
            getData(token, "3", eventBean.getSendStr(), "", "", 1);
        } else if (eventBean.getSendCode() == 20) {
            getData(token, "3", "", "", "", 1);
        }

    }
}